import axios from 'axios';
import qs from 'qs'
import Vue from 'vue'
import { Message } from 'element-ui'
import config from '../config'
Vue.component(Message)

//window.baseUrl = 'http://192.168.1.100:7081/byjz-ia', //内网

const service = axios.create({
    headers: {
        'Content-Type': 'application/json; charset=utf-8'
    },
    // process.env.NODE_ENV === 'development' 来判断是否开发环境
    // easy-mock服务挂了，暂时不使用了
    baseURL: config.baseApi,
    timeout: 10000000
});

service.interceptors.request.use(
    config => {
        if (!config.headContype) {
            config.data = qs.stringify(config.data)
            config.headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
        }
        config.headers['token'] = sessionStorage.getItem('token')
        config.headers['userId'] = encodeURIComponent(sessionStorage.getItem('userId'))

        return config;
    },
    error => {
        return Promise.reject();
    }
);

service.interceptors.response.use(
    response => { //成功请求到数据
        if (response.status === 200) {
            if (response.data.code == '004') {
                Message.error({ message: response.data.message })
                window.location.href = "/"
            }
         
            else if (response.data.code != '0000') {
                Message.error({ message: response.data.message })
                return response.data;
            }
            else {
                return response.data;
            }

        } else {
            Promise.reject();
        }
    },
    error => { //响应错误处理

        console.log('error:=========================================');
        console.log(error);
        console.log(JSON.stringify(error));

         //错误 解构
        const{
            response:{status,data}
        }=error;


        if(status===500){

            Message.error({ message: data.message })

        }else{
            Message.error({ message: '网络超时请稍后再试' })

        }

        //debugger;

        return Promise.reject();
    }
);

export default service;
